#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
邮件发送模块
用于发送新闻日报邮件
"""

import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from datetime import datetime
import os
from typing import List, Dict, Optional


class EmailSender:
    """邮件发送器"""
    
    def __init__(self, smtp_server: str, smtp_port: int, email: str, password: str, use_ssl: bool = False):
        """
        初始化邮件发送器
        
        Args:
            smtp_server: SMTP服务器地址
            smtp_port: SMTP端口
            email: 发送邮箱
            password: 邮箱密码或授权码
            use_ssl: 是否使用SSL直连
        """
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.email = email
        self.password = password
        self.use_ssl = use_ssl
    
    def send_news_daily(self, 
                       to_email: str, 
                       news_data: Dict, 
                       ai_analysis: str = None) -> bool:
        """
        发送新闻日报邮件
        
        Args:
            to_email: 接收邮箱
            news_data: 新闻数据
            ai_analysis: AI分析内容
            
        Returns:
            发送是否成功
        """
        try:
            # 创建邮件内容
            subject = f"📰 新闻日报 - {datetime.now().strftime('%Y年%m月%d日')}"
            html_content = self._create_html_content(news_data, ai_analysis)
            text_content = self._create_text_content(news_data, ai_analysis)
            
            # 创建邮件
            msg = MIMEMultipart('alternative')
            msg['From'] = self.email
            msg['To'] = to_email
            msg['Subject'] = subject
            
            # 添加文本和HTML内容
            text_part = MIMEText(text_content, 'plain', 'utf-8')
            html_part = MIMEText(html_content, 'html', 'utf-8')
            
            msg.attach(text_part)
            msg.attach(html_part)
            
            # 发送邮件
            server = None
            try:
                if self.use_ssl:
                    context = ssl.create_default_context()
                    server = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port, context=context)
                else:
                    server = smtplib.SMTP(self.smtp_server, self.smtp_port)
                    server.ehlo()
                    server.starttls()
                    server.ehlo()

                server.login(self.email, self.password)
                server.send_message(msg)

                print(f"✅ 新闻日报已发送至 {to_email}")
                return True

            finally:
                if server is not None:
                    try:
                        server.quit()
                    except Exception as close_err:
                        print(f"⚠️  邮件发送成功，但退出SMTP会话时出现警告: {type(close_err).__name__}: {close_err}")
        except Exception as e:
            print(f"❌ 邮件发送失败: {type(e).__name__}: {e}")
            return False
    
    def _create_html_content(self, news_data: Dict, ai_analysis: str = None) -> str:
        """
        创建HTML格式的邮件内容
        
        Args:
            news_data: 新闻数据
            ai_analysis: AI分析内容
            
        Returns:
            HTML内容
        """
        today = datetime.now().strftime('%Y年%m月%d日')
        
        html = f"""
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>新闻日报 - {today}</title>
            <style>
                body {{
                    font-family: 'Microsoft YaHei', Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                    max-width: 800px;
                    margin: 0 auto;
                    padding: 20px;
                    background-color: #f5f5f5;
                }}
                .container {{
                    background-color: white;
                    padding: 30px;
                    border-radius: 10px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                }}
                .header {{
                    text-align: center;
                    border-bottom: 3px solid #007bff;
                    padding-bottom: 20px;
                    margin-bottom: 30px;
                }}
                .header h1 {{
                    color: #007bff;
                    margin: 0;
                    font-size: 28px;
                }}
                .header p {{
                    color: #666;
                    margin: 10px 0 0 0;
                    font-size: 16px;
                }}
                .news-item {{
                    border-left: 4px solid #007bff;
                    padding: 15px 20px;
                    margin: 20px 0;
                    background-color: #f8f9fa;
                    border-radius: 0 5px 5px 0;
                }}
                .news-title {{
                    font-size: 18px;
                    font-weight: bold;
                    color: #007bff;
                    margin-bottom: 10px;
                }}
                .news-title a {{
                    color: #007bff;
                    text-decoration: none;
                }}
                .news-title a:hover {{
                    text-decoration: underline;
                }}
                .news-meta {{
                    color: #666;
                    font-size: 14px;
                    margin-bottom: 10px;
                }}
                .news-description {{
                    color: #555;
                    line-height: 1.5;
                }}
                .ai-analysis {{
                    background-color: #e8f4fd;
                    border: 1px solid #007bff;
                    border-radius: 5px;
                    padding: 20px;
                    margin: 30px 0;
                }}
                .ai-analysis h3 {{
                    color: #007bff;
                    margin-top: 0;
                }}
                .footer {{
                    text-align: center;
                    margin-top: 30px;
                    padding-top: 20px;
                    border-top: 1px solid #ddd;
                    color: #666;
                    font-size: 14px;
                }}
                .stats {{
                    background-color: #f8f9fa;
                    padding: 15px;
                    border-radius: 5px;
                    margin-bottom: 20px;
                    text-align: center;
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>📰 新闻日报</h1>
                    <p>{today} | 来源: {news_data.get('title', '36kr')}</p>
                </div>
                
                <div class="stats">
                    <strong>📊 今日新闻统计</strong><br>
                    总条目数: {news_data.get('total_items', 0)} | 
                    精选条目: {len(news_data.get('items', []))} | 
                    更新时间: {news_data.get('last_updated', '未知')}
                </div>
        """
        
        # 添加新闻条目
        for i, item in enumerate(news_data.get('items', []), 1):
            html += f"""
                <div class="news-item">
                    <div class="news-title">
                        <a href="{item.get('link', '#')}" target="_blank">
                            {i}. {item.get('title', '无标题')}
                        </a>
                    </div>
                    <div class="news-meta">
                        📅 {item.get('published', '未知时间')}
                        {f"| 👤 {item.get('author', '')}" if item.get('author') else ''}
                    </div>
                    <div class="news-description">
                        {self._truncate_text(item.get('description', '暂无描述'), 120)}
                    </div>
                </div>
            """
        
        # 添加AI分析
        if ai_analysis:
            html += f"""
                <div class="ai-analysis">
                    <h3>🤖 AI智能分析</h3>
                    <div style="white-space: pre-line;">{ai_analysis}</div>
                </div>
            """
        
        html += """
                <div class="footer">
                    <p>📧 此邮件由MorningByte新闻日报系统自动发送</p>
                    <p>🕐 发送时间: """ + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + """</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        return html
    
    def _create_text_content(self, news_data: Dict, ai_analysis: str = None) -> str:
        """
        创建纯文本格式的邮件内容
        
        Args:
            news_data: 新闻数据
            ai_analysis: AI分析内容
            
        Returns:
            纯文本内容
        """
        today = datetime.now().strftime('%Y年%m月%d日')
        
        text = f"""
📰 新闻日报 - {today}
{'=' * 50}

📊 今日新闻统计:
- 来源: {news_data.get('title', '36kr')}
- 总条目数: {news_data.get('total_items', 0)}
- 精选条目: {len(news_data.get('items', []))}
- 更新时间: {news_data.get('last_updated', '未知')}

📰 今日要闻:
{'=' * 50}
"""
        
        # 添加新闻条目
        for i, item in enumerate(news_data.get('items', []), 1):
            text += f"""
{i}. {item.get('title', '无标题')}
   📅 时间: {item.get('published', '未知时间')}
   🔗 链接: {item.get('link', '无链接')}
   📝 内容: {self._truncate_text(item.get('description', '暂无描述'), 120)}
   
"""
        
        # 添加AI分析
        if ai_analysis:
            text += f"""
🤖 AI智能分析:
{'=' * 50}
{ai_analysis}

"""
        
        text += f"""
{'=' * 50}
📧 此邮件由MorningByte新闻日报系统自动发送
🕐 发送时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
"""
        
        return text
    
    def _truncate_text(self, text: str, max_length: int) -> str:
        """
        截断文本到指定长度
        
        Args:
            text: 原始文本
            max_length: 最大长度
            
        Returns:
            截断后的文本
        """
        if not text:
            return ''
        
        if len(text) <= max_length:
            return text
        
        # 截断到指定长度，并添加省略号
        return text[:max_length] + "..."


def create_qq_email_sender(email: str, password: str) -> EmailSender:
    """
    创建QQ邮箱发送器
    
    Args:
        email: QQ邮箱地址
        password: QQ邮箱授权码
        
    Returns:
        EmailSender实例
    """
    return EmailSender(
        smtp_server="smtp.qq.com",
        smtp_port=465,
        email=email,
        password=password,
        use_ssl=True
    )


def main():
    """测试邮件发送功能"""
    # 测试配置 - 请替换为实际的邮箱和授权码
    test_email = "your_email@qq.com"
    test_password = "your_authorization_code"
    to_email = "505735255@qq.com"
    
    # 创建测试新闻数据
    test_news = {
        'title': '36kr新闻测试',
        'description': '测试新闻源',
        'last_updated': '2024-01-01 08:00:00',
        'total_items': 3,
        'items': [
            {
                'title': '测试新闻标题1',
                'link': 'https://example.com/news1',
                'published': '2024-01-01 07:00:00',
                'description': '这是第一条测试新闻的描述内容...'
            },
            {
                'title': '测试新闻标题2',
                'link': 'https://example.com/news2',
                'published': '2024-01-01 08:00:00',
                'description': '这是第二条测试新闻的描述内容...'
            }
        ]
    }
    
    test_analysis = "这是AI分析的测试内容，包含对新闻的智能分析和趋势预测。"
    
    # 创建邮件发送器
    sender = create_qq_email_sender(test_email, test_password)
    
    # 发送测试邮件
    success = sender.send_news_daily(to_email, test_news, test_analysis)
    
    if success:
        print("✅ 测试邮件发送成功！")
    else:
        print("❌ 测试邮件发送失败！")


if __name__ == "__main__":
    main()
